/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package neuron.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import common.statistics.NormalDist;
import common.statistics.NormalDistImpl;

/**
 *
 * @author rlaakso
 */
public class OctaveParser {

    public static class StatsRow {
        public double n, mean, stdev, min, max;

        public StatsRow(double[] data) {
            n = data[0];
            mean = data[1];
            stdev = data[2];
            min = data[3];
            max = data[4];
        }

    }

    Map<String, Object> data;

    public OctaveParser(File file) throws IOException {

        data = new HashMap<String, Object>();

        BufferedReader br = new BufferedReader(new FileReader(file));
        while (true) {
            String line = br.readLine();

            // EOF
            if (line == null) break;

            // empty or comment
            if (line.trim().length() == 0 ||
                line.charAt(0) == '#') {
                continue;
            }

            StringTokenizer st = new StringTokenizer(line);
            String var = st.nextToken();
            String eq = st.nextToken();
            if (eq.charAt(0) != '=') {
                throw new IOException("Parse error! '" + line +"'");
            }
            String value = st.nextToken();

            if (value.charAt(0) != '[') {
            // simple value
                data.put(var, value);
            }
            else {
                // array
                List<double[]> matrix = new ArrayList<double[]>();
                int row = 0;
                while(true) {
                    String l = br.readLine();
                    if (l.startsWith("];")) break;
                    StringTokenizer t2 = new StringTokenizer(l);
                    int tokens = t2.countTokens();
                    double[] rowData = new double[tokens];
                    for (int col = 0; col < tokens; col++) {
                        rowData[col] = Double.parseDouble(t2.nextToken());
                    }
                    matrix.add(rowData);
                }
                data.put(var, matrix);
            }
        }
    }

    public List<double[]> getMatrix(String name)
    {
        return (List<double[]>) data.get(name);
    }

    public NormalDist getDistribution(String name)
    {
        List<double[]> matrix = getMatrix(name);
        double[] data = matrix.get(matrix.size()-1); // get last record
        OctaveParser.StatsRow ts = new OctaveParser.StatsRow(data);
        return new NormalDistImpl(ts.mean, ts.stdev);
    }


}
